<?php
namespace Mobile\Controller;

class LoginController extends BaseController {

    public $smscodeModel;
    public function __construct() {
        parent::__construct();
        
        $this->smscodeModel = new \Mobile\Model\smscodeModel();
    }

    public function index(){
        if(IS_AJAX){
            $uid = get('uid');
            $pw = get('pw');
             $len = strlen($uid);
            if($len>=11){
                $where = array(
                    'mobile' => $uid,
                );
            }else{
                $where = array(
                    'uid' => $uid,
                );
            }
            $res = $this->memberModel->where($where)->find();
            if(!$res) {
                return_json(1,'密码不正确');
            }
            if($res['try_time']>=30) {
                return_json(1,'禁止登录');
            }
            $pw = md5($pw.C('SALT'));
            if($res['password']!=$pw) {
                $this->memberModel->where($where)->setInc('try_time');
                //return_json(1,'密码不正确');
            }
            
            $this->memberModel->where($where)->setField('try_time',0);
            
            if(!$res){
                return_json(1,'密码不正确');
            }else{
                session('memberinfo',$res);
                session('uid',$res['uid']);
                parent::autoLogin(true);
                return_json(0,"登录成功","","/mobile/user");
            }
        }
        $seo_data = array(
            "title" => C('SITE_NAME'),
            "keywords" => "",
        );
        $this->setSeo($seo_data);
//        layout(false);
        $this->display('index1');
    }
    
    public function changepw() {
        if (IS_AJAX) {
            $allow = array('password_old', 'password_new1', 'password_new2');
            $data = param_filter($_POST, $allow);

            if (!$data['password_old']) {
                return_json(1, "请输入旧密码");
            }

            if (!$data['password_new1']) {
                return_json(1, "请输入新密码");
            }

            if (!$data['password_new2']) {
                return_json(1, "请确认新密码");
            }

            if ($data['password_new1'] != $data['password_new2']) {
                return_json(1, "两次输入密码不一致");
            }

            $uid = session('uid');

            if (!$uid) {
                session_destroy();
                return_json(0, "请先登录", '', "/mobile/login/");
            }

            $res = $this->memberModel->where(array('uid' => $uid))->getField('password');
            if ($res != md5($data['password_old'].C("SALT"))) {
                return_json(1, "旧密码输入错误");
            }
            checkPassword($data['password_new1']);
            $pw = md5($data['password_new1'].C('SALT'));
            $res = $this->memberModel->where(array('uid' => $uid))->setField('password', $pw);

            if ($res) {
                session_destroy();
                return_json(0, "修改成功,请重新登录", '', "/mobile/login/");
            } else {
                return_json(1, "网络错误");
            }
        }
        $seo_data = array(
            "title" => '修改密码',
            "description" => "",
            "keywords" => "",
        );
        layout('Mui/layout');
        $this->setSeo($seo_data);
        $this->display();
    }

    public function quit(){
        session_destroy();
        header('Location: /mobile/login');
    }
    
     public function resetpw() {
        
        if(IS_AJAX){
            $allow = array(
                'mobile','smscode','code_id','password'
            );
            $data = param_filter($_POST, $allow);
            $where = array(
                'mobile'=>$data['mobile'],
            );
            $member = $this->memberModel->where($where)->find();
            
            if(!$member) {
                return_json(1,'用户不存在');
            }
            
            if(strlen($data['password'])<6) {
                return_json(1,'密码必须大于6位');
            }
            checkPassword($data['password']);
//            _pr($data['password']);
            $this->_checkCode($data);
            $saveData = array(
                'password' => md5($data['password'].C('SALT')),
                'try_time' => 0
            );
            $res = $this->memberModel->where($where)->save($saveData);
            if($res) {
                return_json(0,'修改成功','','/mobile/login');
            }
            return_json(1,'密码与旧密码相同');
            
        }
        $seo_data = array(
            "title" => '忘记密码',
            "description" => "",
            "keywords" => "",
        );
//        layout('Mui/layout');
        $this->setSeo($seo_data);
        $this->display('resetpw');
    }


    /*
     * 发送手机验证码
     */
    public function sendsms(){
       
        $mobile = get('mobile');
        if(!check_mobile($mobile)){
            return_json(1,"请检查手机号是否正确");
        }
        
       /*  $mem = $this->memberModel->where(array('mobile'=>$mobile))->find();
        if(empty($mem)) {
            return_json(1,"手机号码不存在");
        } */
        
        if(!IS_AJAX){
            return_json(1,"提交方式有误");
        }
        
        //判断是否超出频率限制
        //短信验证码，使用同一个签名，对同一个手机号码发送短信验证码，允许每分钟1条，累计每小时7条。
        $time1 = date("Y-m-d H:i:s");//当前时间
        $time2 = date("Y-m-d H:i:s",time()-60);//60秒前
        $time3 = date("Y-m-d H:i:s",time()-60*60);//1小时前
        $today1 = date("Y-m-d H:i:s",strtotime(date("Y-m-d")));//今天的时间

        $where_min = array(
            "mobile" => $mobile,
            "send_status" => 1,
            "create_time" => array(
                "between" => array(
                    $time1,$time2
                )
            )
        );
        $count_min = $this->smscodeModel->getSmscodeCount($where_min);
        if($count_min>=1){
            return_json(1,"请稍等60秒后重新获取");
        }
        
        $where_hour = array(
            "mobile" => $mobile,
            "send_status" => 1,
            "create_time" => array(
                "between" => array(
                    $time1,$time3
                )
            )
        );
        $count_hour = $this->smscodeModel->getSmscodeCount($where_hour);
        if($count_hour>=7){
            return_json(1,"请稍等1个小时后重新获取");
        }
       
        //发送短信
        $code = rand(1000,9999);
        $data = array(
            "code" => "$code",
            "product" => C('SMS_SIGN')
        );
        
        //将信息存储到数据库
        $save_data = array(
            "uid" => $this->uid,
            "smssign" => C('ALIDAYU_SIGN'),
            "mobile" => $mobile,
            "tmpid" => C('ALIDAYU_SHENFEN_TMP'),
            "content" => json_encode($data),
            "code" => $code,
            "create_time" => date("Y-m-d H:i:s"),
            "expired_time" => date("Y-m-d H:i:s",time()+5*60),
            "ip" => get_client_ip(),
            "try_time" => 0,
            "status" => 1,
        );
        
        $res = alisms(C('ALIDAYU_SIGN'),$mobile,C('ALIDAYU_SHENFEN_TMP'),$data);
        if($res['result']['success']){
            //发送成功
            //存储数据
            $save_data['send_status'] = 1;
            $code_id = $this->smscodeModel->addSmscode($save_data);
            return_json(0,"",$code_id);
        }else{
            //发送失败
            //echo $resp['result']['err_code'];
            $msg = "发送失败,请稍后重试。错误原因:".$res['sub_msg'];
            $save_data['send_status'] = 0;
            $this->smscodeModel->addSmscode($save_data);
            return_json(1,$msg);
            //短信验证码，使用同一个签名，对同一个手机号码发送短信验证码，允许每分钟1条，累计每小时7条。
            //短信通知，使用同一签名、同一模板，对同一手机号发送短信通知，允许每天50条（自然日）。
        }
        
    }
    
    
    protected function _checkCode($data){
        if(!$data['code']) {
            return_json(1,'请输入验证码');
        }
        //检查验证码是否正确
        $codewhere = array(
            //"code_id" => $data['code_id'],
            "code" => $data['code'],
            "mobile" => $data['mobile'],
        );
        $res = $this->smscodeModel->where($codewhere)->find();
        $code_id=$res['code_id'];
        if(!$res){
            //将尝试次数加1
            $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
            return_json(1,"验证码错误");
        }
        
      //  if($res['ip'] != $ip){
          //  $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
          //  return_json(1,"你的网络有风险,已阻止此次验证!");
     //   }
        
        /*if(strtotime($res['expired_time']) < time()){
            return_json(1,"验证码已过期,请重新获取!");
        }*/
        
        if($res['try_time'] > 2){
            return_json(1,"验证码已失效,请重新获取!");
        }
        
        if($res['status'] != 1){
            return_json(1,"验证码已失效,请重新获取!");
        }
        
        //验证通过
        //将验证码作废
        $this->smscodeModel->where(array("code_id"=>$code_id))->setInc('try_time');//将尝试次数加1
        $this->smscodeModel->where(array("code_id"=>$code_id))->setField('status',0);
        return true;
        
    }

    public function register () {
        if(IS_AJAX) {
            $allow = array(
                'realname','mobile','code_id','idcard','refer_uid','code','pay_password','pay_password_confirm','grade_id','user_province','user_city','user_county'
            );
            $must = array(
                'realname','mobile','idcard','code','pay_password','pay_password_confirm'
            );
            
            $data = param_filter($_POST, $allow,$must,false,true);
			$this->_checkCode($data);
            if(empty($data)) {
                return_json(1,'请填写完整');
            }
            if(!check_mobile($data['mobile'])) {
                return_json(1,'手机号格式不正确');
            }
            $memberModel = M('member');
            $where = array('mobile'=>$data['mobile']);
            $om = $memberModel->where($where)->find();
            if($om) {
                return_json(1,'手机号已存在');
            }
            
            if($data['refer_uid']) {
                $refer = $memberModel->where(array('uid'=>$data['refer_uid']))->find();
                if(!$refer) {
                    return_json(1,'推荐人不存在');
                }
                $data['refer_nickname'] = $refer['realname'];
            }

            if($data['pay_password']!=$data['pay_password_confirm']) {
                return_json(1,'支付密码不一致');
            }
            unset($data['pay_password_confirm']);
            $data['pay_password'] = md5($data['pay_password'].C('SALT'));
            
            $data['create_time'] = date('Y-m-d H:i:s');
            $idcard = $data['idcard'];
            $len = strlen($idcard);
            if($len != 18){
                return_json(1,"身份证号码填写错误,请重新填写");
            }
            $oldid = $this->memberModel->where(array('idcard'=>$idcard))->find();
            if($oldid) {
                //return_json(1,"身份证号码填写错误,请重新填写");
            }
            $pass = substr($idcard, -6);
            $data['password'] = md5($pass.C('SALT'));
            $data['grade_id'] = 1;
            $res = $memberModel->add($data);
            if($res) {
                return_json(0,'已提交，请登陆','',"/mobile/login");
            }
            return_json(1,'提交失败，请重试');
        }


        // $gradearr = M('grade')->field('grade_id,grade_name')->select();
        // $this->assign('gradearr',$gradearr);
        $seo_data = array(
            "title" => '注册',
            "description" => "",
            "keywords" => "",
        );
        $this->setSeo($seo_data);
        $this->display();
    }
    
    public function upload() {
        $type = 'admin';
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     15145728 ;// 设置附件上传大小
        $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =  "/";
        $upload->savePath  = "/upload/".$type."/";
        // 上传文件 
        $info   =   $upload->upload();
        if(!$info) {// 上传错误提示错误信息
            $this->error($upload->getError());
        }else{// 上传成功
            return_json(0,'',$info['upfile']['savepath'].$info['upfile']['savename']);
        }
    }
    
    protected function _newuserMsg($userinfo,$newuser){
        $tmp_id = $this->tmpl['NEW_USER']['tmp_id'];
        $content = '新用户注册提醒';
        $footer ="请尽快登录后台进行审核".'\\n\\n';
        $color = '#000';
        $msg = array(
            "touser" => $userinfo['openid'],
            "template_id" => $tmp_id,
            'url' => $url,
            "topcolor" => $color,
            'data' => array(
                'first' => array(
                    'value' => urlencode($content.'\\n'),
                    'color' => $color
                ),
                'keyword1' => array(
                    'value' => urlencode($newuser['realname']),
                    'color' => $color,
                ),
                'keyword2' => array(
                    'value' => urlencode($newuser['mobile']),
                    'color' => $color,
                ),
                'keyword3' => array(
                    'value' => urlencode(date('Y-m-d H:i:s')),
                    'color' => $color,
                ),
                'remark' => array(
                    'value' => urlencode($footer),
                    'color' => $color,
                ),
            ),
        );
        $msgttt = array(
            "uid" => $userinfo['uid'],
            "openid" => $userinfo['openid'],
            "nickname" => $userinfo['nickname'],
            "groupid" => -1,
            "content" => urldecode(json_encode($msg)),
            "send_priority" => 1,
            "create_time" => time(),
            "send_time" => time(),
            "status" => -1,
            "send_plan_time" => time()
        );
        $tmpmsgModel = new \Mobile\Model\tmpmsgModel();
        $tmpmsgModel->addtmpmsg($msgttt);//添加消息到数据库队列
        return true;
    }
 
}